/**
 * 
 */
package com.seguriapp.controllers;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.database.MergeCursor;
import android.util.Log;

import com.seguriapp.communication.WebServiceConsumer;
import com.seguriapp.dao.EntityCategoryDao;
import com.seguriapp.dao.EntityDao;
import com.seguriapp.data.DataSource;
import com.seguriapp.entities.CrimeCategoryEntity;
import com.seguriapp.entities.Entity;
import com.seguriapp.entities.EntityType;
import com.seguriapp.entities.POIMarker;
import com.seguriapp.sync.EntityTask;

/**
 * @author pjohnson
 */
public class EntityController {

	private Context mContext;

	public EntityController(final Context context) {
		mContext = context;
	}

	public void insertInitialEntities() {
		EntityTask entTask = new EntityTask(mContext);
		entTask.execute();
	}

	public void insertListEntities(JSONArray jSonEntities) {
		for (int i = 0; i < jSonEntities.length(); i++) {
			try {
				mContext.getContentResolver().insert(
						EntityDao.CONTENT_URI,
						EntityDao.contentValuesToInsert(jSonEntities
								.getJSONObject(i)));
			} catch (JSONException e) {
				Log.e("JsonError", e.getMessage());
			}
		}

	}

	/**
	 * @param filtro
	 * @return
	 */
	public Cursor fetchEntities(final String filtro) {
		String selection;
		if ("".equals(filtro)) {
			selection = null;
		} else {
			selection = EntityDao.COL_TITLE + " like '%" + filtro + "%' ";
		}
		MatrixCursor extras = new MatrixCursor(new String[] { "_id",
				"idEntity", "title", "url", "longitude", "altitude",
				"latitude", "type" });
		extras.addRow(new String[] { "-1", "-1", "Seleccione Comisaria", "",
				"0", "0", "0", "0" });

		Cursor cursor = mContext.getContentResolver().query(
				EntityDao.CONTENT_URI, null, selection, null, null);

		Cursor[] cursors = { extras, cursor };
		Cursor extendedCursor = new MergeCursor(cursors);
		// final String sortOrder = EntityDao.TABLE_NAME + "." +
		// EntityDao.COL_TITLE + " ASC ";
		return extendedCursor;
	}

	public int deleteEntities() {
		return mContext.getContentResolver().delete(EntityDao.CONTENT_URI,
				null, null);
	}

	public void refreshEntities() {
		deleteEntities();
		insertInitialEntities();
	}

	public List<POIMarker> getEntityList(double latitude, double longitude, String typeId) {
		final WebServiceConsumer webConsumer = WebServiceConsumer
				.getInstance(mContext);
		ArrayList<POIMarker> lstEntities = new ArrayList<POIMarker>();
		try {
			final JSONObject postObject = new JSONObject();
			postObject.put("latitude", latitude);
			postObject.put("longitude", longitude);
			postObject.put("categoriesList", typeId);

			final String jSon = webConsumer.getEntities(postObject);
			final JSONArray entitiesArray = new JSONObject(jSon)
					.getJSONArray("entitiesList");

			for (int i = 0; i < entitiesArray.length(); i++) {
				final JSONObject entityJson = entitiesArray.getJSONObject(i);
				final POIMarker marker = new POIMarker(
						entityJson.getString("title"),
						entityJson.getDouble("latitude"),
						entityJson.getDouble("longitude"), 0,
						entityJson.getString("url"),
						DataSource.DATASOURCE.OWNURL);

				marker.setDistance(entityJson.getDouble("distance"));
				marker.setEntityId(entityJson.getInt("id"));
				lstEntities.add(marker);
			}

		} catch (final JSONException e) {
			lstEntities = null;
			Log.e("Error Json", e.getMessage());
		}

		return lstEntities;
	}

	public List<Entity> getEntityListForMap(final String type, double latitude, double longitude) {
		final WebServiceConsumer webConsumer = WebServiceConsumer
				.getInstance(mContext);
		ArrayList<Entity> lstEntities = new ArrayList<Entity>();
		try {
			final JSONObject postObject = new JSONObject();
			postObject.put("latitude", latitude);
			postObject.put("longitude", longitude);
			postObject.put("categoriesList", type);

			final String jSon = webConsumer.getEntities(postObject);
			final JSONArray entitiesArray = new JSONObject(jSon)
					.getJSONArray("entitiesList");

			for (int i = 0; i < entitiesArray.length(); i++) {
				final JSONObject entityJson = entitiesArray.getJSONObject(i);
				final Entity entity = new Entity();
				entity.setLongitude(entityJson.getDouble("longitude"));
				entity.setLatitude(entityJson.getDouble("latitude"));
				entity.setDistance(entityJson.getDouble("distance"));
				entity.setNombre(entityJson.getString("title"));
				entity.setTelefono(entityJson.getString("phone"));

				lstEntities.add(entity);
			}

		} catch (final JSONException e) {
			lstEntities = null;
			Log.e("Error Json", e.getMessage());
		}

		return lstEntities;
	}

	/**
	 * Obtiene de la BD local las categorias de los crímenes
	 * 
	 * @return
	 */
	public Cursor getEntityCategories() {
		return mContext.getContentResolver().query(
				EntityCategoryDao.CONTENT_URI, null, null, null, null);
	}

	public void updateSelectedCategory(final CrimeCategoryEntity category) {
		mContext.getContentResolver().update(EntityCategoryDao.CONTENT_URI,
				EntityCategoryDao.contentValuesToUpdate(category),
				EntityCategoryDao.COL_CID + " = ?",
				new String[] { String.valueOf(category.getIdCategory()) });
	}

	public int getEntityById(String eId) {
		final String selection = EntityDao.TABLE_NAME + "." + EntityDao.COL_EID
				+ " = ?";
		final Cursor cursor = mContext.getContentResolver().query(
				EntityDao.CONTENT_URI, null, selection, new String[] { eId },
				null);
		int id = cursor.getInt(cursor.getColumnIndexOrThrow(EntityDao.COL_ID));
		return id;

	}

	public ArrayList<EntityType> getEntityTypeList() {
		final WebServiceConsumer webConsumer = WebServiceConsumer
				.getInstance(mContext);
		ArrayList<EntityType> lstEntities = new ArrayList<EntityType>();
		final String categories = webConsumer.getEntityCategories();
		try {
			final JSONArray jSonArray = new JSONObject(categories).getJSONArray("entityTypeList");
			for (int i = 0; i < jSonArray.length(); i++) {
				final JSONObject json = jSonArray.getJSONObject(i);
				final EntityType type = new EntityType();
				type.setDescription(json.getString("description"));
				type.setId(json.getString("id"));
				type.setName(json.getString("name"));

				lstEntities.add(type);
			}
		} catch (JSONException e) {
			Log.e("JSON Error", e.getMessage());
		}

		return lstEntities;
	}
}
